package com.itmuch.contentcenter.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {

    @Resource
    private NacosDiscoveryProperties nacosDiscoveryProperties;



    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        try {
            BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            String name = baseLoadBalancer.getName();
            log.info("他触发的名称={}",name);
            String clusterName = nacosDiscoveryProperties.getClusterName();
            log.info("clusterName={}",clusterName);
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            //所有的实例
            List<Instance> instances = namingService.selectInstances(name, true);
            //所有的该集群节点实例
            List<Instance> instancesSameCluster = instances.stream()
                    .filter(instance -> Objects.equals(instance.getClusterName(), clusterName))
                    .collect(Collectors.toList());
            List<Instance> chosenInstance = new ArrayList<>();
            //如果相同集群为空则选择所有的实例
            if (CollectionUtils.isEmpty(instancesSameCluster)){
             chosenInstance = instances;
             log.info("跨区域调动，instances={},name={}",chosenInstance,name);
            }else{
               chosenInstance = instancesSameCluster;
            }
            //根据权重算法，选择返回一个实例
            Instance instance = ExtendBalancer.getHostByRandomWeight2(chosenInstance);
            log.info("选择了该例子，instance={},port={}",instance,instance.getPort());
            return new NacosServer(instance);
        } catch (NacosException e) {
            e.printStackTrace();
            return null;
        }
    }
}

class ExtendBalancer extends Balancer{
    public static Instance getHostByRandomWeight2(List<Instance> hosts){
     return getHostByRandomWeight(hosts);
    }
}
